package com.mazaiting.demo.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.SecureRandom;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 动态线程池
 *
 * @author mazaiting
 * @create_time 2022/10/5 14:08
 */
@Slf4j
@RestController
@RequiredArgsConstructor
public class DynamicTpController {

    private final ThreadPoolExecutor dtpExecutor1;

    private final SecureRandom secureRandom = new SecureRandom();

    /**
     * 测试线程池
     */
    @GetMapping("dtp")
    public void test() {
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                int sum = secureRandom.nextInt(300);
//                log.info("随机数线程数: {}", sum);
                for (int i = 0; i < sum; i++) {
//                    int finalI = i;
                    dtpExecutor1.execute(() -> {
//                        log.info("test" + finalI);
                        try {
                            TimeUnit.SECONDS.sleep(1);
                        } catch (InterruptedException ignored) {}
                    });
                }
            }
        }, 0, 40 * 1000);
    }

}
